<script setup>
import { addOrg, deleteOrg, updateOrgApi, findTree } from '@/api/system/organization'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search, Refresh, Plus } from '@element-plus/icons-vue'
import { usePagination } from '@/hooks/usePagination'
import AddOrganization from './components/AddOrganization.vue'

const loading = ref(false)
const addOrganizationRef = ref(null)
const pageData = reactive({
  isShowAddDialog: false,
  editingId: '',
  parentId: '',
  orgType: '' // TOP_ORG、ORG
})

const toAddTopOrg = () => {
  pageData.orgType = 'TOP_ORG'
  pageData.parentId = '0'
  pageData.isShowAddDialog = true
}

const createOrg = (record) => {
  addOrg(record)
    .then(() => {
      ElMessage.success('新增成功')
      pageData.isShowAddDialog = false
      getTableData()
    })
    .finally(() => {
      addOrganizationRef.value.submitBtnLoading = false
    })
}

const updateOrg = (record) => {
  updateOrgApi(record)
    .then(() => {
      ElMessage.success('修改成功')
      pageData.isShowAddDialog = false
      getTableData()
    })
    .finally(() => {
      addOrganizationRef.value.submitBtnLoading = false
    })
}

const handleDelete = (row) => {
  ElMessageBox.confirm(`正在删除组织：${row.name}，确认删除？`, 'Warning', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    deleteOrg(row.id).then(() => {
      ElMessage.success('删除成功')
      getTableData()
    })
  })
}

const handleUpdate = (row) => {
  pageData.editingId = row.id
  pageData.isShowAddDialog = true
}

const handleCreate = (row) => {
  if (row.level >= 5) {
    ElMessage.warning('最多新建5级！')
    return
  }
  pageData.orgType = 'ORG'
  pageData.editingId = ''
  pageData.parentId = row.id
  pageData.isShowAddDialog = true
}

const tableData = ref([])
const searchFormRef = ref()
const searchData = reactive({
  name: ''
})
const getTableData = () => {
  loading.value = true
  const param = {
    name: searchData.name
  }
  findTree(param)
    .then((res) => {
      tableData.value = addLevel(res.data, 0)
    })
    .catch(() => {
      tableData.value = []
    })
    .finally(() => {
      loading.value = false
    })
}
// treeData添加层级
const addLevel = (data, level) => {
  const res = []
  level++
  data.forEach((node) => {
    const n = {
      ...node,
      level
    }
    if (n.children) {
      n.children = addLevel(n.children, level)
    }
    res.push(n)
  })
  return res
}
const resetSearch = () => {
  searchFormRef.value?.resetFields()
  getTableData()
}

getTableData()
</script>

<template>
  <div class="app-container">
    <div v-hasPermi="['sysOrgManager:post:findTree']" shadow="never" class="search-wrapper">
      <el-form ref="searchFormRef" :inline="true" :model="searchData">
        <el-form-item prop="name" label="组织名称">
          <el-input v-model="searchData.name" placeholder="请输入组织名称" maxlength="50" clearable />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" :icon="Search" @click="getTableData">查询</el-button>
          <el-button :icon="Refresh" @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
    </div>
    <el-card>
      <div v-loading="loading" shadow="never">
        <div class="toolbar-wrapper">
          <div>
            <el-button v-hasPermi="['sysOrgManager:post:add']" type="primary" plain :icon="Plus" @click="toAddTopOrg">
              新增顶级组织
            </el-button>
          </div>
        </div>
        <div class="table-wrapper">
          <el-table :data="tableData" row-key="id" default-expand-all max-height="70vh">
            <el-table-column prop="name" label="组织名称" />
            <el-table-column prop="type" label="组织类型" align="center">
              <!-- 组织类型 1机构 2部门 -->
              <template #default="scope">
                {{ scope.row.type === 1 ? '机构' : '部门' }}
              </template>
            </el-table-column>
            <el-table-column prop="showOrder" label="显示顺序" align="center" />
            <el-table-column prop="status" label="状态" align="center">
              <!-- 状态 0启用 1停用 -->
              <template #default="scope">
                <el-tag v-if="scope.row.status === 0" type="success" effect="plain">启用</el-tag>
                <el-tag v-else type="danger" effect="plain">停用</el-tag>
              </template>
            </el-table-column>
            <el-table-column fixed="right" label="操作" width="220" align="center">
              <template #default="scope">
                <el-button
                  v-hasPermi="['sysOrgManager:post:add']"
                  type="primary"
                  text
                  bg
                  size="small"
                  @click="handleCreate(scope.row)"
                >
                  新增
                </el-button>
                <el-button
                  v-hasPermi="['sysOrgManager:put:update']"
                  type="primary"
                  text
                  bg
                  size="small"
                  @click="handleUpdate(scope.row)"
                >
                  修改
                </el-button>
                <el-button
                  v-hasPermi="['sysOrgManager:delete:delete']"
                  type="danger"
                  text
                  bg
                  size="small"
                  @click="handleDelete(scope.row)"
                >
                  删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </div>
    </el-card>

    <AddOrganization
      ref="addOrganizationRef"
      v-model:visible="pageData.isShowAddDialog"
      :id="pageData.editingId"
      :parentId="pageData.parentId"
      :orgType="pageData.orgType"
      @create="createOrg"
      @update="updateOrg"
    />
  </div>
</template>

<style lang="scss" scoped>
.search-wrapper {
  :deep(.el-card__body) {
    padding-bottom: 2px;
  }
}

.toolbar-wrapper {
  display: flex;
  justify-content: space-between;
  margin-bottom: 20px;
  :deep(.el-button) {
    padding: 6px 12px;
  }
}

.table-wrapper {
  margin-bottom: 20px;
}
</style>
